const {
  getList,
  zhongshu,
  newBlog,
  updateBlog,
  delBlog
} = require('../controller/blog')

var formidable = require('formidable')
var express = require('express');
var router = express.Router();
const {
  SuccessModel,
  ErrorModel
} = require('../model/resModel')

// 获取博客列表
router.get('/list', (req, res, next) => {
  let {
    page,
    limit
  } = req.query;
  // 获取分页数据
  const result = getList(page, limit)
  // 获取总数
  const result1 = zhongshu()
  var data
  result.then(listData => {
    // 把分页数据赋值出去
    data = listData
  })
  return result1.then(listData1 => {
    //  接收返回
    res.json({
      errno: 0,
      data: data,
      count: listData1
    })
  })

});

// 图片上传
router.post('/tp', (req, res, next) => {
  var form = new formidable.IncomingForm(); //创建上传表单
  form.encoding = 'utf-8'; //设置编辑
  form.uploadDir = 'public/images'; //设置上传目录


  form.keepExtensions = true; //保留后缀
  form.maxFieldsSize = 2 * 1024 * 1024; //文件大小

  form.parse(req, function (err, fields, files) {

    if (err) {
      res.locals.error = err;
      res.render('index', {
        title: TITLE
      });
      return;
    }
    //console.log(files);

    var extName = 'png'; //后缀名
    switch (files.file.type) {
      case 'image/pjpeg':
        extName = 'jpg';
        break;
      case 'image/jpeg':
        extName = 'jpg';
        break;
      case 'image/png':
        extName = 'png';
        break;
      case 'image/x-png':
        extName = 'png';
        break;
    }

    if (extName.length == 0) {
      res.locals.error = '只支持png和jpg格式图片';
      res.render('index', {
        title: TITLE
      });
      return;
    }
    //显示地址；
    var showUrl1 = files.file.path.split('\\')[1];
    var showUrl2 = files.file.path.split('\\')[2];
    var showUrl = showUrl1 + "/" + showUrl2
    console.log(showUrl);
    res.json({
      data: showUrl
    })

  });
})

// 新建一篇博客
router.post('/new', (req, res, next) => {
  // console.log(req.body);
  try {
    const result = newBlog(req.body)
    result.then(data => {
      res.json(
        new SuccessModel(data)
      )
    })
  } catch (error) {
    next(error)
  }
})

// 更新一篇博客
router.post('/update', (req, res, next) => {
  // console.log(req.body);
  try {
    const result = updateBlog(req.body)
    result.then(val => {
      if (val) {
        res.json(
          new SuccessModel()
        )
      } else {
        res.json(
          new ErrORModel('更新博客失败')
        )
      }
    })
  } catch (error) {
    next(error)
  }

})

// 删除一篇博客
router.post('/del', (req, res, next) => {
  try {
    const result = delBlog(req.body.id)
    result.then(val => {
      if (val) {
        res.json(
          new SuccessModel()
        )
      } else {
        res.json(
          new ErrORModel('删除博客失败')
        )
      }
    })
  } catch (error) {
    next(error)
  }
})

module.exports = router;